package Forms;

import Classes.*;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Owner
 */
public class Subject_Manage extends javax.swing.JFrame {
    static MInterface mi;
    
    static User cUser;
    static ArrayList<ClassLevel> clevelList;
    static CurrDetails cd;
    static String stat;
    static Subject subj;

    /**
     * Creates new form CurriculumSchoolYear
     */
    public Subject_Manage(User user, MInterface i, ArrayList<ClassLevel> cl, CurrDetails c, String ss, Subject subb) {
        initComponents();
        this.setLocationRelativeTo(getRootPane());
        mi = i;
        cUser = user;
        clevelList = (ArrayList<ClassLevel>) cl.clone();
        cd = c;
        stat = ss;
        subj = subb;
        
        for(int x = 0; x < clevelList.size(); x++) {
            clevelCB.addItem(clevelList.get(x).getClassName());
        }      
        
        if(stat.equals("Edit")) {
            clevelCB.setSelectedItem(subj.getClassName());
            name.setText(subj.getSubjName());
            desc.setText(subj.getDesc());

            if(subj.getUnits().equals("None")) {
                units.setText("");
            } else {
                units.setText(subj.getUnits());
            }
        }
        
        
        
        toggleUnits();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        clevelCB = new javax.swing.JComboBox();
        cancel = new javax.swing.JButton();
        save = new javax.swing.JButton();
        name = new javax.swing.JTextField();
        jLabel45 = new javax.swing.JLabel();
        jLabel46 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        desc = new javax.swing.JTextArea();
        jLabel47 = new javax.swing.JLabel();
        units = new javax.swing.JTextField();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Subject Management");

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/banner.jpg"))); // NOI18N
        jLabel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel2.setText("Class Level:");

        jSeparator1.setForeground(new java.awt.Color(0, 102, 51));

        clevelCB.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        clevelCB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clevelCBActionPerformed(evt);
            }
        });

        cancel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cancel.setText("Cancel");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        save.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        save.setText("Save");
        save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveActionPerformed(evt);
            }
        });

        jLabel45.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel45.setText("Subject Name:");

        jLabel46.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel46.setText("Description:");

        desc.setColumns(20);
        desc.setRows(5);
        jScrollPane1.setViewportView(desc);

        jLabel47.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel47.setText("Units:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel45)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(name))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(clevelCB, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jSeparator1)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(save)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancel))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 552, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel47)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(units, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel46))
                        .addGap(423, 423, 423)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(clevelCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel45)
                    .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel46)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel47)
                    .addComponent(units, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancel)
                    .addComponent(save))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
        this.setVisible(false);
        cd.load2a();
    }//GEN-LAST:event_cancelActionPerformed

    private void saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveActionPerformed
        if(name.getText().isEmpty() || desc.getText().isEmpty()) {
                JOptionPane.showMessageDialog (null, "Empty Textbox!", "Error", JOptionPane.ERROR_MESSAGE);
        } else if(units.getText().isEmpty() && units.isEnabled()) {
                JOptionPane.showMessageDialog (null, "Empty Textbox!", "Error", JOptionPane.ERROR_MESSAGE);
        } else {
            if(stat.equals("Edit")) {
                try {
                    boolean existing = false;
                    ArrayList<Subject> ccc = (ArrayList<Subject>) mi.getList2("getlist2-subj", clevelList.get(clevelCB.getSelectedIndex()).getCurrclID(), null).clone();
                    for(int y = 0; y < ccc.size(); y++) {
                        if(ccc.get(y).getSubjName().equals(name.getText()) && !ccc.get(y).getSubjName().equals(subj.getSubjName())) {
                            existing = true;
                        }
                    }
                    
                    if(existing) {
                        JOptionPane.showMessageDialog(null, name.getText() + " already exists!", "Error", JOptionPane.ERROR_MESSAGE);
                    } else {
                        Subject ss = new Subject(subj.getsubID(), name.getText(), desc.getText(), units.getText());
                        ss.setClassID(clevelList.get(clevelCB.getSelectedIndex()).getClassID());
                        ss.setUnits("0");
                        if(clevelList.get(clevelCB.getSelectedIndex()).getClassCategory().equals("High School")) {
                            ss.setUnits(units.getText());
                        }
                        
                        boolean s = false;
                        s = mi.edit("edit-subject", ss, cUser);
                        if(s) {
                            JOptionPane.showMessageDialog(null, "Subject Successfully Updated.", "Error", JOptionPane.INFORMATION_MESSAGE);
                            cd.load2a();
                            this.setVisible(false);
                        } else {
                            JOptionPane.showMessageDialog(null, "A Server/Database error has occurred!", "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } catch(Exception e) {
                    e.printStackTrace();
                }
            } else {
                String clID = clevelList.get(clevelCB.getSelectedIndex()).getClassID();
                try {
                    ArrayList<Subject> subj = (ArrayList<Subject>) mi.getList2("getlist2-clevel-subj", clID, null).clone(); 
                    Subject s = new Subject(null, name.getText(), desc.getText(), units.getText());
                    boolean existing = false;
                    for(int x = 0; x < subj.size(); x++) {
                        if(s.getSubjName().equals(subj.get(x).getSubjName())) {
                            existing = true;
                        }
                    }

                    if(existing) {
                        JOptionPane.showMessageDialog(null, "Subject already exists!", "Error", JOptionPane.ERROR_MESSAGE);
                    } else {
                        s.setClassID(clID);
                        s.setUnits("0");
                        if(clevelList.get(clevelCB.getSelectedIndex()).getClassCategory().equals("High School")) {
                            s.setUnits(units.getText());
                        }
                        boolean success = mi.add("add-subject", s, "", cUser);

                        if(success) {
                            JOptionPane.showMessageDialog(null, "Subject Successfully Added.", "Success", JOptionPane.INFORMATION_MESSAGE);
                            name.setText("");
                            desc.setText("");
                            units.setText("");
                            cd.load2a();
                        } else {
                            JOptionPane.showMessageDialog(null, "A Server/Database error has occurred!", "Error", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }//GEN-LAST:event_saveActionPerformed

    private void clevelCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clevelCBActionPerformed
        toggleUnits();
    }//GEN-LAST:event_clevelCBActionPerformed

    public void toggleUnits() {
        System.out.println("lll " + clevelList.get(clevelCB.getSelectedIndex()).getClassCategory());
        if(!clevelList.get(clevelCB.getSelectedIndex()).getClassCategory().equals("High School")) {
            units.setEnabled(false);
            units.setText("");
        } else {
            units.setEnabled(true);
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Subject_Manage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Subject_Manage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Subject_Manage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Subject_Manage.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Subject_Manage(cUser, mi, clevelList, cd, stat, subj).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancel;
    private javax.swing.JComboBox clevelCB;
    private javax.swing.JTextArea desc;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel45;
    private javax.swing.JLabel jLabel46;
    private javax.swing.JLabel jLabel47;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField name;
    private javax.swing.JButton save;
    private javax.swing.JTextField units;
    // End of variables declaration//GEN-END:variables
}
